//
//  YZBaseWebViewController.m
//  VET
//
//  Created by YZ on 2018/7/17.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZBaseWebViewController.h"

@interface YZBaseWebViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

@property (nonatomic, strong, readwrite) WKWebView *webView;

/**
 进度条
 */
@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, copy) NSString *url;

@property (nonatomic, strong) NSArray<NSString *> *functions;

@end

@implementation YZBaseWebViewController

- (instancetype)initWithUrl:(NSString *)url registerFunctions:(NSArray<NSString *> *)functions
{
    if (self = [super init]) {
        _url = url;
        _functions = functions;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self config];
    self.navigationController.navigationBar.translucent = NO;
    //加载请求
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
}

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)config
{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//    // 设置偏好设置
    config.preferences = [[WKPreferences alloc] init];
    // 默认为0
    config.preferences.minimumFontSize = 10;
    // 默认认为YES
    config.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    // web内容处理池
    config.processPool = [[WKProcessPool alloc] init];
    // 通过JS与webview内容交互
    config.userContentController = [[WKUserContentController alloc] init];
    
    // 注入JS对象名称function，当JS通过function来调用时，
    // 我们可以在WKScriptMessageHandler代理中接收到
    for (NSString *function in _functions) {
        [config.userContentController addScriptMessageHandler:self name:function];
    }
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - YZ_BOTTOM_MARGIN - self.tabBarController.tabBar.bounds.size.height) configuration:config];
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    // 导航代理
    self.webView.navigationDelegate = self;
    // 与webview UI交互代理
    self.webView.UIDelegate = self;
    //kvo
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"progress: %f", self.webView.estimatedProgress);
        self.progressView.alpha = 1;
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES] ;
        if (self.progressView.progress == 1) {
            [UIView animateWithDuration:0.5 animations:^{
                self.progressView.alpha = 0;
            }];
        }
    }
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,
    // NSDictionary, and NSNull类型
    NSLog(@"%@", message.body);
    [self customUserContentController:userContentController didReceiveScriptMessage:message];
}

#pragma mark - WKUIDelegate

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    [self customWebView:webView runJavaScriptAlertPanelWithMessage:message initiatedByFrame:frame completionHandler:completionHandler];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    [self customWwebView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];
    //decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler
{
    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}

#pragma mark -- setters && getters

- (void)setWebViewFrame:(CGRect)rect
{
    self.webView.frame = rect;
}

- (void)setProgressViewFrame:(CGRect)rect
{
    self.progressView.frame = rect;
}

- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.frame = CGRectMake(0, 0, kScreenWidth, 2);
        _progressView.progressTintColor = kColorWithHex(0x32BE60);
        _progressView.backgroundColor = [UIColor clearColor];
    }
    return _progressView;
}

@end
